<?php

class Dcmp_Web_Application extends Kd_Web_Application {
	
	private $_domain = NULL;
    
    public function getDomain(){
    	return $this->_domain;
    }

    protected function initialize() {
    	Kd_Web_Config::setRouterClass('Dcmp_Web_Router');
    	Kd_Web_Config::setIdentityClass('Dcmp_Web_Identity');
    	
    	Kd_Loader::addScope(explode(',', $this->getConfig()->getSetting('versions')));
    	
    	$domainSettings = $this->getConfig()->getSetting('domain');
    	$baseUrl = $this->getConfig()->getSetting('baseUrl', '/');
    	$url = substr($_SERVER['REQUEST_URI'], strlen($baseUrl));
		
    	$domainSetting = NULL;
        foreach($domainSettings as $setting){
        	if(strcmp(Kd_Util_String::subString($url, '/'), $setting['urlName']) == 0){
        		$domainSetting = $setting;
        		
        	}
        }
        
        if(is_null($domainSetting)){
        	foreach($domainSettings as $setting){
        		if(array_key_exists('default', $setting) && $setting['default']){
        			$domainSetting = $setting;
        		}
        	}
        }

        $domainClass = Kd_Loader::loadClass($domainSetting['name'].'_domain');
        $this->_domain = new $domainClass($this, $domainSetting);
        
        Kd_Db_Config::setTablePrefix($this->getConfig()->getSetting('db.tablePrefix'));
        $connectionSettings = $this->getConfig()->getSetting('db.connections');
        foreach ($connectionSettings as $connectionSetting) {
            Kd_Db_Config::registerConnection(
                            $connectionSetting['name'],
                            $connectionSetting['driver'],
                            $connectionSetting['server'],
                            $connectionSetting['database'],
                            $connectionSetting['username'],
                            $connectionSetting['password'],
                            TRUE);
        }        
        parent::initialize();
    }
    
    protected function route() {
    	$this->currentStep = 'route';
    	$this->nextStep = 'filter';
    	Kd_Web::getRouter()->setDomain($this->getDomain()->getConfig()->getSetting('urlName'));
    }
    
    protected function handler(){
    	$this->_domain->run();
    	parent::handler();
    }
    
    protected function output(){
        $content = Kd_Web::getResponse()->getContent();
        if (preg_match_all('/\{\{lang\s"([a-zA-Z0-9.-_]+)"\}\}/iU', $content, $matches)) {
            $atts = $matches[0];
            $langKeys = $matches[1];
            $attCount = count($atts);
            for ($i = 0; $i < $attCount; $i++) {
                $langKey = $langKeys[$i];
                $content = str_replace($atts[$i], Kd_Localize_Helper::__($langKey), $content);
            }
        }        
        Kd_Web::getResponse()->setContent($content);
        parent::output();   	
    }
}